/**
 *
 */
package org.jeecg.modules.com.pointoperation.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Xuan_zhen
 *
 */
@Slf4j
public class StringClass {
	public static String GetClientIP(HttpServletRequest request) {
		String ip = "";
		try {
			ip = request.getHeader("x-forwarded-for");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			if (ip == null) {
				ip = "";
			}
		} catch (Exception ex) {
			ip = "";
		}
		return ip;
	}

	public static String GetHostIP(HttpServletRequest request) {
		String localIP = "";
		try {
			InetAddress addr;
			addr = InetAddress.getLocalHost();
			localIP = addr.getHostAddress().toString();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return localIP;
	}

	public static String TrimEnd(String s, char c) {
		int p = s.length() - 1;
		while (s.charAt(p) == c && p >= 0)
			p--;
		if (p < 0)
			return "";
		return s.substring(0, p + 1);
	}

	/**
	 * inputStream转String
	 *
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static String inputStream2String(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		while ((i = is.read()) != -1) {
			baos.write(i);
		}
		String content = new String(baos.toByteArray(), "UTF-8");
		return content;
	}

	// #region 生成随机的纯字母的字符串

	/// <summary>
	/// 生成随机的纯字母的字符串
	/// </summary>
	/// <param name="length">要获取的字符串长度</param>
	/// <returns></returns>
	public static String GetRandom(int length) {
		char[] Pattern = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
				'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
		String result = "";
		int n = Pattern.length;

		for (int i = 0; i < length; i++) {
			int rnd = (int) (Math.random() * n);
			result += Pattern[rnd];
		}
		return result;
	}

	public static String GetRandoms(int length) {
		char[] Pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','A',
				'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
				'W', 'X', 'Y' };
		String result = "";
		int n = Pattern.length;
		for (int i = 0; i < length; i++) {
			int rnd = (int) (Math.random() * n);
			result += Pattern[rnd];
		}
		return result;
	}
	/// <summary>
	/// 生成随机的数字+字母的字符串
	/// </summary>
	/// <param name="length">要获取的字符串长度</param>
	/// <returns></returns>
	public static String GetAllRandom(int length) {
		char[] Pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
				'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A',
				'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
				'W', 'X', 'Y', 'Z' };
		String result = "";
		int n = Pattern.length;
		for (int i = 0; i < length; i++) {
			int rnd = (int) (Math.random() * n);
			result += Pattern[rnd];
		}
		return result;
	}

	/// <summary>
	/// 生成随机的纯数字的字符串
	/// </summary>
	/// <param name="length">要获取的字符串长度</param>
	/// <returns></returns>
	public static String GetRandomNumber(int length) {
		char[] Pattern = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
		String result = "";
		int n = Pattern.length;
		for (int i = 0; i < length; i++) {
			int rnd = (int) (Math.random() * n);
			result += Pattern[rnd];
		}
		return result;
	}

	/**
	 * 获取某个范围内的随机数,只能取到（max-1）
	 * @param min
	 * @param max
	 * @return
	 */
	public static int GetRandom(int min, int max){
	    Random random = new Random();
	    int s = random.nextInt(max) % (max - min + 1) + min;
	    return s;
	}

	/*
	 * 时间戳，精确到秒
	 */
	public static String GetTimeStamp() {
		String nowTick = (new Date()).getTime() + "";
		return nowTick.substring(0, nowTick.length() - 4);
	}

	private static Pattern pattern = Pattern.compile("[0-9]*");

	/**
	 * 判断是否纯数字
	 *
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * 将string字符串转成int数组
	 *
	 * @param ids
	 * @return
	 */
	public static int[] convertStringToIntArray(String ids) {
		String[] IDStirng = ids.split(",");
		int[] intTemp = new int[IDStirng.length];
		for (int i = 0; i < IDStirng.length; i++) {
			intTemp[i] = Integer.parseInt(IDStirng[i]);
		}
		return intTemp;
	}

	/**
	 * 将List<String>转成'A','B'...的格式
	 *
	 * @param strList
	 * @return
	 */
	public static String convertListToString(List<String> strList) {
		String newString = "";
		for (int i = 0; i < strList.size(); i++) {
			if (newString != "")
				newString += ",";
			newString += "'" + strList.get(i) + "'";
		}
		return newString;
	}

	/**
	 * 将字符串转成A****格式
	 *
	 * @param str
	 * @return
	 */
	public static String changeString(String str) {
		try {
			if (StringUtils.isNotBlank(str)) {
				int size = str.length();// 字符串的长度，为了知道有几个x
				String subStr = str.substring(0, 1);
				String replaceX = "";
				for (int i = 1; i < size; i++) {
					replaceX += "*";
				}
				String finalStr = subStr + replaceX;// as+xxx
				return finalStr;
			} else {
				return "**";
			}
		} catch (Exception e) {
			log.error(e.toString()+ "changeString.ex======");
			return "**";
		}
	}

	public static String completionString(int length, String end) {
		String str = "";
		if (end.length() < length) {
			for (int i = 0; i < length - end.length(); i++) {
				str += "0";
			}
			str += end;
		} else {
			str = end;
		}
		return str;
	}

	public static String filterEmoji(String source) {
        if(source != null)
        {
            Pattern emoji = Pattern.compile ("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE | Pattern . CASE_INSENSITIVE ) ;
            Matcher emojiMatcher = emoji.matcher(source);
            if ( emojiMatcher.find())
            {
                source = emojiMatcher.replaceAll("*");
                return source ;
            }
        return source;
       }
       return source;
    }

	public static boolean isMobile(String code){
		if(StringUtils.isNotBlank(code) && code.length()==11){
			return true;
		}
		return false;
	}


	/**
	 * 将字符串转成 A* 或者 A***A
	 * add by lsz 2019年10月29日
	 * @param str
	 * @return
	 */
	public static String changeFirstAndLastString(String str) {
		try {
			if (StringUtils.isNotBlank(str)) {
				// 控制截取字符串
				int size = str.length();
				// 控制 * 的数量
				int count = str.length();
				// * 前面的字符串
				String firstStr = "";
				// * 前面的字符串
				String lastStr = "";
				// *
				String replaceX = "";
				// 最终拼接成的字符串
				String finalStr = "";

				//字段的长度为 1 ,直接返回不做处理
				if(size == 1){
					return str;
				}

				//验证开始部分是否含有emoji表情
				String temp1 = str.substring(0, 2);
				if (verifyEmoji(temp1)) {
					firstStr = str.substring(0, 2);
					count -= 2;
				} else {
					firstStr = str.substring(0, 1);
					count -= 1;
				}

				//长度大于2，返回格式 A***A
				if (size > 2) {
					//验证结束部分是否含有emoji
					String temp2 = str.substring(size - 2);
					if (verifyEmoji(temp2)) {
						if(count == 2){
							// 此时
							lastStr = "*";
							count -= 2;
						}else{
							lastStr = str.substring(size - 2);
							count -= 2;
						}
					} else {
						lastStr = str.substring(size - 1);
						count -= 1;
					}
				}
				for (int i = 0; i < count; i++) {
					replaceX += "*";
				}
				finalStr = firstStr + replaceX + lastStr;
				return finalStr;
			} else {
				return "**";
			}
		} catch (Exception e) {
			log.error(e.toString()+ "changeFirstAndLastString.ex======");
			return "**";
		}
	}

	/**
	 * 验证字符串是否含有emoji
	 * add by lsz 2019年10月29日
	 * @param str
	 * @return
	 */
	public static boolean verifyEmoji(String str){
		Pattern emoji = Pattern.compile ("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE | Pattern . CASE_INSENSITIVE ) ;
		Matcher emojiMatcher = emoji.matcher(str);
		if (emojiMatcher.find()){
			return true;
		}else {
			return false;
		}
	}
}
